/*jshint esversion: 9 */
/*
 图片文件工具
 */
function dataURLtoFile(dataurl,fileName) {  //将base64编码转回file文件
    var arr = dataurl.split(","),
        mime = arr[0].match(/:(.*?);/)[1], //文件类型
        bstr = atob(arr[1]),
        n = bstr.length,
        u8arr = new Uint8Array(n);
    while (n--) {
        u8arr[n] = bstr.charCodeAt(n);
    }
    return new File([u8arr], fileName || mime);
}
export function compressImg({  //压缩图片
    file,
    maxSize=100,  //最大大小
    maxWidth=300,  //最大宽度，默认高度不能超过宽度的两倍
}={}){  //压缩图片
    var _file;
    var read = new FileReader();
    read.readAsDataURL(file);
    return new Promise((resolve,reject)=>{
        read.onload = function (e) {
            var img = new Image();
            img.src = e.target.result;
            img.onload = function(){
                //默认按比例压缩
                var w = this.width,
                    h = this.height;
                //生成canvas
                var canvas = document.createElement("canvas");
                var ctx = canvas.getContext("2d");
                var base64;
                // 创建属性节点
                canvas.setAttribute("width", maxWidth);
                let _height = h/(w/maxWidth)<maxWidth*2?h/(w/maxWidth):maxWidth*2; //同比例高度，不超过宽度的两倍
                canvas.setAttribute("height", _height);
                ctx.drawImage(this, 0, 0, maxWidth, _height);
                for(let i=0;i<10;i++){ 
                    base64 = canvas.toDataURL('image/jpeg', 1-i/10);  //循环增大压缩比例，直到小于100k
                    _file = dataURLtoFile(base64,file.name); 
                    if(parseFloat(parseInt(_file.size)/1024).toFixed(5) <= maxSize){  //如果文件大小小于限制时跳出循环
                        break;
                    }
                }
                resolve({  // 回调函数返回file的值（将base64编码转成file）
                    base64:base64,
                    file:_file,
                });
            };
            img.onerror = function(e){
                reject(e);
            };
        };
    });
}